package com.engine.utilities;

import com.engine.Engine;

import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * User: cwatts
 * <p/>
 * Date: 12/29/11
 * <p/>
 * MainGamePanel is used to
 */
public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback
{
	private MainThread mainThread;

	private Engine engine;

	public MainGamePanel(Context context, Engine engine)
	{
		super(context);

		getHolder().addCallback(this);

		this.engine = engine;

		// Create a new game thread
		this.mainThread = new MainThread(engine, getHolder(), this);

		setFocusable(true);
	}

	/**
	 * A wrapper for setting the running flag on the main thread.
	 * @param isRunning if true then main thread is running otherwise it is stopped.
	 */
	public void setRunning(boolean isRunning)
	{
		this.mainThread.setRunning(isRunning);
	}

	public void surfaceCreated(SurfaceHolder surfaceHolder)
	{
		// Maybe have setRunning call start.
		this.setRunning(true);
		this.mainThread.start();
	}

	public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2)
	{

	}

	public void surfaceDestroyed(SurfaceHolder surfaceHolder)
	{
		// Try to kill the thread and keep trying until it has been done.
		boolean retry = true;

		while(retry)
		{
			try
			{
				this.mainThread.join();
				retry = false;
			}
			catch (InterruptedException ignored)
			{
			}
		}
	}

	public boolean onTouchEvent(MotionEvent event)
	{
		this.engine.HandleInput(event);
		return super.onTouchEvent(event);
	}

	protected void onDraw(Canvas canvas)
	{

	}
}
